'use strict';

import { Application } from 'egg';
import * as moment from 'moment'
export default function(app: Application) {
  const { STRING, INTEGER} = app.Sequelize;
  const Sub = app.model.define('sub', {
    sub_id: { type: INTEGER, unique: true, autoIncrement: true, primaryKey: true },
    sub_name:{ type: STRING},
    create_time: { 
      type: STRING,
      get:function(){
        return moment(this['dataValues']["create_time"]).format('YYYY-MM-DD HH:mm:ss')
      }
    },
    sort:{
      type:INTEGER
    }
  },{
    tableName:'sub',
    timestamps: false,
    hooks:{
      beforeCreate:async function(instance){
        let result:any=await app.model.Sub.findOne({order:[['sort','DESC']],attributes:['sort']});
        if(result&&result['sort']){
          result=result['sort'];
        }else{
          result=0;
        }
        instance['sort']=result+1;
      },
      beforeFind:async function(options){
        if(Array.isArray(options.order)){
          options.order.unshift(['sort','DESC'])
          //options.order=[['sort','ASC']]
        }
      }
    }
  });
  

  return class extends Sub {
    static associate() {
    }
  }
}